<template>
  <el-dialog
    :title="modelWay == 'binding' ? '用户（浙政）绑定' : '用户（浙政）修改'"
    :visible.sync="visible"
    width="800px"
    append-to-body
    :before-close="handleClose"
  >
    <div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="form.nickName"
                placeholder="请输入用户昵称"
                maxlength="30"
                v-if="statusFlag == 1"
              />
              <el-autocomplete
                v-else
                v-model="form.nickName"
                :fetch-suggestions="searchnickName"
                placeholder="请输入用户昵称"
                @select="handleSelectname"
                @blur="checkNickname"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <Treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
                size="small"
                :disabled="disabledFlag"
              >
              </Treeselect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
                :disabled="disabledFlag"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
                :disabled="disabledFlag"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- v-if="form.userId == undefined || form.userId == null" -->
            <el-form-item
              label="用户账号"
              prop="userName"
              v-if="statusFlag != 1"
            >
              <el-input
                v-model="form.userName"
                placeholder="请输入用户账号"
                maxlength="30"
                :disabled="disabledFlag"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- v-if="form.userId == undefined || form.userId == null" -->
            <el-form-item
              label="用户密码"
              prop="password"
              v-if="!disabledFlag && statusFlag != 1"
            >
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select
                v-model="form.sex"
                placeholder="请选择性别"
                :disabled="disabledFlag"
              >
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status" :disabled="disabledFlag">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select
                v-model="form.postIds"
                multiple
                placeholder="请选择岗位"
                :disabled="disabledFlag"
              >
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select
                v-model="form.roleIds"
                multiple
                placeholder="请选择角色"
                :disabled="disabledFlag"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                maxlength="100"
                show-word-limit
                placeholder="请输入内容"
                :disabled="disabledFlag"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" @click="submit">确 定</el-button>
      <el-button size="small" @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getUser, updateUser } from "@/api/system/user";
import { bindingDing, getNickname } from "@/api/basicdata/binding";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  props: {
    visible: { type: Boolean, default: false },
    modelWay: { type: String, default: "" },
    statusFlag: { type: [String, Number], default: "" },
    id: { type: [String, Number], default: "" },
    accountId: { type: String, default: "" },
    employeeCode: { type: String, default: "" },
  },
  dicts: ["sys_normal_disable", "sys_user_sex"],
  data() {
    return {
      form: {
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        // password: null,
        phonenumber: null,
        email: null,
        sex: null,
        status: "0",
        remark: null,
        postIds: [],
        roleIds: [],
      },
      // 昵称集合
      nameoptions: [],
      // 部门树选项
      deptOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      disabledFlag: true,
      selectFlag: false,
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.statusJudge();
          if (this.id != null && this.id != "") {
            this.getUserinfo(this.id);
          } else {
            this.getAdddata();
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {
    this.getTreeselect();
  },
  methods: {
    // 状态判断钩子
    statusJudge() {
      console.log(this.statusFlag);
      switch (this.statusFlag) {
        case 0:
          // 未绑定
          this.disabledFlag = false;
          break;
        case 1:
          // 已绑定
          this.disabledFlag = false;
          break;
        case 2:
          // 已解绑
          this.disabledFlag = true;
          break;
        case 3:
          // 停用
          this.disabledFlag = true;
          break;
      }
    },
    // 获取用户详情
    getUserinfo(id) {
      // console.log("userid", id);
      getUser(id)
        .then((res) => {
          // console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.postOptions = res?.posts ?? [];
          this.roleOptions = res?.roles ?? [];
          this.form = res?.data ?? {};
          this.form.postIds = res?.postIds ?? [];
          this.form.roleIds = res?.roleIds ?? [];
        })
        .catch((err) => {});
    },
    // 获取新增时数据
    getAdddata() {
      getUser()
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.postOptions = res?.posts;
          this.roleOptions = res?.roles;
        })
        .catch((err) => {});
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    //todo 模糊查询用户昵称
    searchnickName(queryString, cb) {
      this.form.nickName = queryString;
      this.selectFlag = false;
      this.nameoptions = [];
      if (queryString != "" && queryString != null) {
        getNickname(queryString)
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            let arr = res?.data ?? [];
            // console.log(arr);
            if (arr.length > 0) {
              arr.map((item) => {
                let obj = {
                  userId: item.userId,
                  value: item.nickName,
                };
                this.nameoptions.push(obj);
                var restaurants = this.nameoptions;
                var results = restaurants;
                // var results = queryString
                //   ? restaurants.filter(this.createStateFilter(queryString))
                //   : restaurants;
                cb(results);
              });
            }
          })
          .catch((err) => {
            // this.$message.error("系统错误,请联系管理员!20083");
          });
      }
    },
    // createStateFilter(queryString) {
    //   return (state) => {
    //     return (
    //       state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    //     );
    //   };
    // },
    //todo 下拉选择用户昵称
    handleSelectname(item) {
      this.form.nickName = item.value;
      this.getUserinfo(item.userId);
      this.selectFlag = true;
    },
    // 失焦触发
    checkNickname() {
      if (this.statusFlag != 1) {
        // console.log(this.selectFlag, 111);
        let a = this.selectFlag; // 及时触发失焦
        setTimeout(() => {
          // console.log(this.selectFlag, 222);
          let b = this.selectFlag; // 延时触发失焦
          if (a === b) {
            // 两者相等则是输入新名称，清空表单（除昵称） 解除限制输入
            this.form = {
              userId: null,
              deptId: null,
              userName: null,
              nickName: this.form.nickName,
              password: null,
              phonenumber: null,
              email: null,
              sex: null,
              status: "0",
              remark: null,
              postIds: [],
              roleIds: [],
            };
            this.disabledFlag = false;
          } else {
            this.disabledFlag = true;
          }
        }, 1000);
      }
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          switch (this.statusFlag) {
            case 0:
              // 未绑定
              this.add(this.form);
              break;
            case 1:
              // 已绑定
              this.update(this.form);
              break;
            case 2:
              // 已解绑
              this.add(this.form);
              break;
            case 3:
              // 停用
              break;
          }
        }
      });
    },
    // todo 修改用户
    update(params) {
      params.password = undefined;
      updateUser(params).then((res) => {
        if (res.code === 700) {
          this.$message.warning(res.msg);
          return false;
        }
        this.$modal.msgSuccess("修改成功");
        this.handleClose(true);
      });
    },
    //todo 绑定请求
    add(form) {
      let params = {};
      if (!this.disabledFlag) {
        params = {
          employeeCode: this.employeeCode,
          accountId: this.accountId,
          userId: null,
          sysUser: { ...form },
        };
      } else {
        params = {
          employeeCode: this.employeeCode,
          accountId: this.accountId,
          userId: form.userId,
        };
      }
      bindingDing(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$modal.msgSuccess("绑定成功");
          this.handleClose(true);
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20082");
        });
    },
    handleClose(flag) {
      this.reset();
      this.$emit("close", typeof flag == "boolean" ? flag : false);
    },
    reset() {
      this.form = {
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        password: null,
        phonenumber: null,
        email: null,
        sex: null,
        status: "0",
        remark: null,
        postIds: [],
        roleIds: [],
      };
      this.selectFlag = false;
      this.disabledFlag = true;
      this.resetForm("form");
    },
  },
};
</script>

<style lang="scss" scoped>
</style>
